<template>
  <el-tabs type="card" v-model="activeName" @tab-click="">
    <el-tab-pane label="考试列表" name="first">
      <div class="main">
        <div class="topBlock">
          <el-button @click="" size="medium" icon="el-icon-plus"></el-button>
          <!--          <el-button @click="" size="medium" icon="el-icon-delete-solid"></el-button>-->
        </div>
        <el-table
            :header-cell-style="{'border': 'none',textAlign:'center'}"
            :cell-style="{'border': 'true',textAlign:'center',}"
            :data="examListWithDuration"
            style="width: 100%">

          <el-table-column type="expand">
            <template slot-scope="props">
              <el-form label-position="left" class="demo-table-expand">
                <el-form-item label="-试卷描述:" style="height: 20px">
                  <span>{{ props.row.paper.paperDesc }}</span>
                </el-form-item>
              </el-form>
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号"/>
          <el-table-column label="试卷名" prop="paper.paperTitle"/>
          <el-table-column label="测试名" prop="examName"/>
          <el-table-column label="考试状态">
            <template slot-scope="{ row }" style="display: flex;  flex-direction: row;">
              <!--                  必须传递对象给value-style-->
              <el-statistic
                  :value-style="valueStyle"
                  v-if="new Date() < new Date(row.startTime)"
                  :value="new Date(row.startTime).getTime()"
                  format="HH:mm:ss"
                  title=""
                  time-indices
              ></el-statistic>
              <span v-else-if="new Date() > new Date(row.endTime)" style="color: #F56C6C"><el-tag
                  type="info">已结束</el-tag></span>
              <span v-else-if="row.answerStatus"><el-tag type="success">已交卷</el-tag></span>
              <span v-else><el-tag type="success">考试中</el-tag></span>
            </template>
          </el-table-column>
          <el-table-column prop="startTime" label="开考时间" :formatter="formatExamStartTime"></el-table-column>
          <el-table-column prop="endTime" label="交卷时间" :formatter="formatExamEndTime"></el-table-column>


          <el-table-column label="考试时间" prop="duration">
            <template slot-scope="scope">
              {{ scope.row.duration }}  <!-- 显示计算得到的持续时间 -->
            </template>
          </el-table-column>
          <el-table-column prop="updateTime" label="发布时间">
            <template slot-scope="scope">
              {{ formatUpdateTime(scope.row.updateTime) }}
            </template>
          </el-table-column>
          <el-table-column label="组织教师" prop="teacher.userName">
            <template slot-scope="scope">
              {{ scope.row.teacher.userName }}  <!-- 显示计算得到的持续时间 -->
            </template>
          </el-table-column>
          <el-table-column prop="id" label="操作" width="300">
            <template slot-scope="scope">
              <!--                <el-button-group>-->
              <el-button type="primary" @click="startExam(scope.row)" size="mini" icon="el-icon-document">开始考试
              </el-button>

            </template>
          </el-table-column>

        </el-table>

      </div>
    </el-tab-pane>

    <el-dialog
        title=""
        :visible.sync="confirmExamVisible"
        width="30%"
        center
    >
      <template slot="title">
        <div style="font-size: 19px;font-weight: bolder">提示</div>
      </template>
      <div style="width: 100%;display: flex;align-items: center;justify-content: center">
        <el-statistic
            :value-style="valueStyleConfirm"
            v-if="new Date() < new Date(confirmExamData.startTime)"
            :value="new Date(this.confirmExamData.startTime).getTime()"
            format="HH:mm:ss"
            title=""
            time-indices
        ></el-statistic>
        <span v-else-if="new Date() > new Date(confirmExamData.endTime)"
              style="color: #F56C6C;font-size: 25px">考试已结束</span>
        <span v-else style="color: #67C23A;font-size: 25px">考试中</span>
      </div>
      <div v-if="confirmExamVisible&&new Date() < new Date(confirmExamData.endTime)"
           style="width: 100%;display: flex;align-items: center;justify-content: center">
        <span
            style="font-size: 18px;margin-top: 20px;font-family: 宋体;font-weight: bolder">{{ confirmExamData.paper.paperTitle }}</span>
      </div>
      <div v-if="confirmExamVisible&&new Date() < new Date(confirmExamData.endTime)"
           style="display: flex;align-items: center;justify-content: center">
        <span
            style="font-size: 18px;margin-top: 20px;font-family: 宋体">单选题:{{ confirmExamData.paper.paperInfo.singleNum }} </span>
        <span
            style="font-size: 18px;margin-top: 20px;font-family: 宋体;margin-left: 25px">多选题:{{ confirmExamData.paper.paperInfo.multipleNum }} </span>
      </div>
      <div v-if="confirmExamVisible&&new Date() < new Date(confirmExamData.endTime)"
           style="display: flex;align-items: center;justify-content: center">
        <span
            style="font-size: 18px;margin-top: 20px;font-family: 宋体">填空题:{{ confirmExamData.paper.paperInfo.fillInNum }} </span>
        <span
            style="font-size: 18px;margin-top: 20px;font-family: 宋体;margin-left: 25px">简答题:{{ confirmExamData.paper.paperInfo.textNum }} </span>
      </div>

      <span slot="footer" class="dialog-footer">
                <el-button @click="confirmExamVisible = false;">取 消</el-button>
                <template v-if="new Date() < new Date(confirmExamData.startTime)"></template>
                <template v-else-if="new Date() > new Date(confirmExamData.endTime)"></template>
                <el-button v-else type="primary" @click="confirmStartExam">确 定</el-button>
      </span>
    </el-dialog>

  </el-tabs>


</template>

<script>
import {getExamListForStuApi} from "@/api/Exam";
import {Storage} from '@/utils/localStorage'
import {Message} from "element-ui";

const storage = new Storage();

export default {
  name: "ExamListStuView",
  data() {
    return {
      valueStyle: {
        fontSize: '15px',
        color: '#409EFF'
      },
      //确认考试隐藏框
      confirmExamVisible: false,
      //确认考试隐藏框数据
      confirmExamData: [],
      //
      valueStyleConfirm: {
        fontSize: '25px',
        color: '#409EFF'
      },
      examList: [],
      activeName: 'first',
    }
  },
  methods: {
    //美观考虑 考试时间的格式化 2023-06-10 00:00 --> 06-10 00:00
    formatExamEndTime(row) {
      // 获取原始时间戳
      const timestamp = new Date(row.endTime);
      // 获取当前时间的年份
      const currentYear = new Date().getFullYear();
      // 获取时间字符串中的年份
      const year = timestamp.getFullYear();
      // 如果当前时间的年份与时间字符串中的年份相同，只显示月日时分，否则显示年月日时分
      if (year === currentYear) {
        return `${(timestamp.getMonth() + 1).toString().padStart(2, '0')}-${timestamp.getDate().toString().padStart(2, '0')} ${timestamp.getHours().toString().padStart(2, '0')}:${timestamp.getMinutes().toString().padStart(2, '0')}`
      } else {
        return row.startTime;
      }
    },
    formatExamStartTime(row) {
      // 获取原始时间戳
      const timestamp = new Date(row.startTime);
      // 获取当前时间的年份
      const currentYear = new Date().getFullYear();
      // 获取时间字符串中的年份
      const year = timestamp.getFullYear();
      // 如果当前时间的年份与时间字符串中的年份相同，只显示月日时分，否则显示年月日时分
      if (year === currentYear) {
        return `${(timestamp.getMonth() + 1).toString().padStart(2, '0')}-${timestamp.getDate().toString().padStart(2, '0')} ${timestamp.getHours().toString().padStart(2, '0')}:${timestamp.getMinutes().toString().padStart(2, '0')}`
      } else {
        return row.startTime;
      }
    },
    confirmStartExam() {
      console.info("this.confirmExamData.paperId", this.confirmExamData.paperId)
      let info = {
        paperId: this.confirmExamData.paperId,
        examId: this.confirmExamData.id
      }
      this.$router.push({
        name: 'PaperStuView',
        params: {
          info: info
        },
      })


    },
    startExam(row) {
      if (row.answerStatus) {
        Message.warning('您已交卷！')
        return
      }
      this.confirmExamVisible = true
      this.confirmExamData = row


      // console.info("this.confirmExamData", this.confirmExamData)
    },
    // 格式化发布时间的函数
    formatUpdateTime(timestamp) {
      if (!timestamp) {
        return '';
      }
      const targetTime = Date.parse(timestamp); // 转换成时间戳
      const now = new Date().getTime(); // 获取当前时间戳
      const diff = Math.abs(now - targetTime); // 获取时间差的绝对值
      const diffMinutes = Math.floor(diff / (1000 * 60)); // 获取时间差的分钟数
      if (diffMinutes < 5) {
        return '刚刚'; // 小于5分钟，表示刚刚发布
      } else if (diffMinutes < 60) {
        return `${diffMinutes} 分钟前`; // 不超过1小时，显示几分钟前
      } else {
        const diffHours = Math.floor(diffMinutes / 60); // 超过1小时，显示几小时前
        if (diffHours < 24) {
          return `${diffHours} 小时前`; // 不超过1天，显示几小时前
        } else {
          const diffDays = Math.floor(diffHours / 24); // 超过1天，显示几天前
          return `${diffDays} 天前`;
        }
      }
    },
    getExamList() {
      let param = storage.getItem("user");
      getExamListForStuApi(param).then(res => {
        if (res.data.code == 200) {
          this.examList = res.data.data.map(exam => {
            const now = new Date()
            const startTime = new Date(exam.startTime)
            exam.countdown = Math.floor((startTime - now) / 1000)
            return exam
          })
          console.info("this.examListWithDuration", this.examListWithDuration)
        }
      })
    }

  },
  created() {
    this.getExamList()
  },
  computed: {
    //将examList转换为带有duration的对象数组
    //在table中绑定的是examListWithDuration
    examListWithDuration() {
      return this.examList.map((row) => {
        const start = new Date(row.startTime); // 创建开始时间的 Date 对象
        const end = new Date(row.endTime); // 创建结束时间的 Date 对象
        const diff = end - start; // 持续时间 = 结束时间 - 开始时间
        const durationInMs = Math.abs(diff); // 取绝对值，避免差值为负数
        const durationInMinutes = durationInMs / (1000 * 60); // 将持续时间转换为分钟
        const durationInHours = Math.floor(durationInMinutes / 60); // 将分钟转换为小时并取整
        const remainingMinutes = durationInMinutes % 60; // 计算剩余的分钟数
        return {
          ...row,
          duration: `${durationInHours} 小时 ${remainingMinutes} 分钟` // 添加新的属性 duration，表示持续时间
        }
      });
    }
  }

}
</script>

<style scoped>


.topBlock {
  display: flex;
  /*background-color: #42b983;*/
  height: 46px;
  align-items: center;
  justify-content: start;
  /*border-left: 1px solid #e6e6e6;*/
  /*border-right: 1px solid #e6e6e6;*/
  /*background-color: #f5f5f5;*/
  border-radius: 5px;
}

.main {
  height: 700px;
  /*background-color: #42b983;*/
}
</style>